﻿using Xejen.Communication.Endpoints;
using Xejen.Communication.Http;
using Xejen.Communication.Http.Abstract;
using Xejen.Communication.Http.Communicator;
using Xejen.Communication.Http.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Xejen.Communication.Test
{
    public partial class MainForm : Form
    {
        private readonly IHttpCommunicator _communicator;
        private readonly IConfiguration _configuration;
        public MainForm(IHttpCommunicator communicator, IConfiguration configuration)
        {
            _communicator = communicator;
            _configuration = configuration;

            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Addresses addresses = new Addresses();
            //_configuration.Bind(addresses);

            //HttpConfig config = new HttpConfig() { };
            //string token = null;
            //NameValueCollection headers = null;
            //WebRequestInvoker request = new WebRequestInvoker(config, token, headers);
            //var result = await request.GetAsync(addresses.GetWeatherForecast.RequestUri);


            //#region 原始的请求方式，全部api自己构建
            //HttpConfig config = new HttpConfig() { };
            //HttpRequestHandler<WebRequestInvoker, HttpConfig> handle = new HttpRequestHandler<WebRequestInvoker, HttpConfig>();

            //HttpCommunicator<WebRequestInvoker> communicator = new HttpCommunicator<WebRequestInvoker>(config, new WebRequestInvokerCreator(), handle);
            //var result1 = await communicator.RequestAsync(new HttpAddressWrapper
            //{
            //    RequestAddress = new Address<HttpAddress>
            //    {
            //        Value = new HttpAddress
            //        {
            //            Method = HttpMethod.GET,
            //            RequestUri = "https://www.baidu.com/"
            //        }
            //    }
            //});

            //var result2 = await communicator.RequestAsync<string>(new HttpAddressWrapper
            //{
            //    RequestAddress = new Address<HttpAddress>
            //    {
            //        Value = new HttpAddress
            //        {
            //            Method = HttpMethod.GET,
            //            RequestUri = "https://www.baidu.com/"
            //        }
            //    }
            //}, "");

            //var returnData = result2.ToString();
            //#endregion
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            Addresses addresses = new Addresses();
            _configuration.Bind(addresses);

            #region 使用依赖注入的方式构建请求
            var result1 = await _communicator.GetAsync(addresses.GetWeatherForecast);
            List<WeatherForecast> weather = result1.DataToString().FromJson<List<WeatherForecast>>(CommunicationSerializerOptions.Normalize);

            var result2 = await _communicator.PostAsync(addresses.PostWeatherForecast, new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽",
                TemperatureC = 38
            });

            var returnData = result2.ToString();

            var result3 = await _communicator.PutAsync(new HttpAddress
            {
                RequestUri = addresses.UpdateWeatherForecast.RequestUri,
            }, new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽",
                TemperatureC = 38
            });

            var result4 = await _communicator.DeleteAsync(addresses.DeleteWeatherForecast);

            var result5 = await _communicator.PostAsync(addresses.Add, 3);

            var result6 = await _communicator.GetAsync(addresses.RandomInt);

            var result7 = await _communicator.PostAsync(addresses.AddRange, new List<WeatherForecastInputModel>
            {
                new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽1",
                TemperatureC = 38
            },
                new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽2",
                TemperatureC = 39
            },
                new WeatherForecastInputModel
            {
                Date = DateTime.Now,
                Summary = "摘要来喽3",
                TemperatureC = 40
            }
            });

            var result8 = await _communicator.GetAsync(addresses.RandomForecastArray);

            #endregion
        }

        public class WeatherForecastInputModel
        {
            // 这里可以定义用于 POST 和 PUT 请求的输入模型
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }
        }

        public class Addresses
        {
            public HttpAddress GetWeatherForecast { get; set; }
            public HttpAddress PostWeatherForecast { get; set; }
            public HttpAddress UpdateWeatherForecast { get; set; }
            public HttpAddress DeleteWeatherForecast { get; set; }
            public HttpAddress Add { get; set; }
            public HttpAddress RandomInt { get; set; }
            public HttpAddress AddRange { get; set; }
            public HttpAddress RandomForecastArray { get; set; }
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            // 构建请求体参数
            string equipmentCode = "1021-CV-EL-00068";
            string resourceCode = "CV-ZYBH2115";
            string localTime = "2020-01-15T10:10:00";
            string operatorUserID = "EQUtest01";
            string operatorPassword = "1";

            // 构建SOAP请求消息体
            string soapBody = $@"
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                <soap:Header>
                    <LoginSoapHeader xmlns=""http://tempuri.org/"">
                        <EquUserID>EQUtest01</EquUserID>
                        <EquPassword>1</EquPassword>
                        <OperatorUserID>{operatorUserID}</OperatorUserID>
                        <OperatorPassword>{operatorPassword}</OperatorPassword>
                    </LoginSoapHeader>
                </soap:Header>
                <soap:Body>
                    <OperatorLogin xmlns=""http://tempuri.org/"">
                        <model>
                            <EquipmentCode>{equipmentCode}</EquipmentCode>
                            <ResourceCode>{resourceCode}</ResourceCode>
                            <LocalTime>{localTime}</LocalTime>
                            <OperatorUserID>{operatorUserID}</OperatorUserID>
                            <OperatorPassword>{operatorPassword}</OperatorPassword>
                        </model>
                    </OperatorLogin>
                </soap:Body>
            </soap:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://122.195.53.162:7008/EquWebService80/EquToMes/EquToMesOperatorLogin.asmx?op=OperatorLogin",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "text/xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                Headers = new System.Collections.Specialized.NameValueCollection
                    {
                        {"EquUserID","EQUtest01" },
                        {"EquPassword","1" },
                        {"OperatorUserID","EQUtest01" },
                        {"OperatorPassword","1" },
                    }
            });

            var str = result2.ToString();
        }

        private async void button5_Click(object sender, EventArgs e)
        {
            //测试通过。注意：XML 声明必须是文档中的第一个节点并且在它之前不允许出现空白字符。
            string soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
              <soap:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>admin</EquUserID>
                  <EquPassword>admin123</EquPassword>
                </LoginSoapHeader>
              </soap:Header>
              <soap:Body>
                <HelloWorld xmlns=""http://tempuri.org/"">
                  <body>
                    <EquipmentCode>strindsasdag</EquipmentCode>
                  </body>
                </HelloWorld>
              </soap:Body>
            </soap:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://192.168.3.164:112/WebService1.asmx?op=HelloWorld",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "text/xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
                Headers = new System.Collections.Specialized.NameValueCollection
                    {
                        {"EquUserID","admin" },
                        {"EquPassword","admin123" },
                    }
            });

            var str = result2.ToString();
        }

        /// <summary>
        /// soap1.2成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            // 构建请求体参数
            string equipmentCode = "1021-CV-EL-00068";
            string resourceCode = "CV-ZYBH2115";
            string localTime = "2020-01-15T10:10:00";
            string operatorUserID = "EQUtest01";
            string operatorPassword = "1";

            // SOAP 1.2请求的URL
            string url = "http://122.195.53.162:7008/EquWebService80/EquToMes/EquToMesOperatorLogin.asmx";

            // 构建SOAP请求的XML内容
            string soapXml = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                <soap12:Header>
                    <LoginSoapHeader xmlns=""http://tempuri.org/"">
                 <EquUserID>EQUtest01</EquUserID>
                  <EquPassword>1</EquPassword>
                  <OperatorUserID>{operatorUserID}</OperatorUserID>
                  <OperatorPassword>{operatorPassword}</OperatorPassword>
                    </LoginSoapHeader>
                </soap12:Header>
                <soap12:Body>
                    <OperatorLogin xmlns=""http://tempuri.org/"">
                        <model>
                    <EquipmentCode>{equipmentCode}</EquipmentCode>
                    <ResourceCode>{resourceCode}</ResourceCode>
                    <LocalTime>{localTime}</LocalTime>
                    <OperatorUserID>{operatorUserID}</OperatorUserID>
                    <OperatorPassword>{operatorPassword}</OperatorPassword>
                        </model>
                    </OperatorLogin>
                </soap12:Body>
            </soap12:Envelope>";

            HttpWebRequest client = (HttpWebRequest)WebRequest.Create(url);
            client.Method = "POST";
            client.ContentType = "application/soap+xml; charset=utf-8";

            client.Headers.Add("SOAPAction", "http://tempuri.org/OperatorLogin");
            client.Headers.Add("EquUserID", "EQUtest01");
            client.Headers.Add("EquPassword", "1");
            client.Headers.Add("OperatorUserID", "EQUtest01");
            client.Headers.Add("OperatorPassword", "1");

            using (var stream = client.GetRequestStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(soapXml);
                }
            }

            using (var response = (HttpWebResponse)client.GetResponse())
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                string soapResponse = streamReader.ReadToEnd();
            }
        }

        private async void button6_Click(object sender, EventArgs e)
        {
            // 构建请求体参数
            string equipmentCode = "1021-CV-EL-00068";
            string resourceCode = "CV-ZYBH2115";
            string localTime = "2020-01-15T10:10:00";
            string operatorUserID = "EQUtest01";
            string operatorPassword = "1";

            // 构建SOAP请求消息体
            string soapBody = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
              <soap12:Header>
                <LoginSoapHeader xmlns=""http://tempuri.org/"">
                  <EquUserID>EQUtest01</EquUserID>
                  <EquPassword>1</EquPassword>
                  <OperatorUserID>{operatorUserID}</OperatorUserID>
                  <OperatorPassword>{operatorPassword}</OperatorPassword>
                </LoginSoapHeader>
              </soap12:Header>
              <soap12:Body>
                <OperatorLogin xmlns=""http://tempuri.org/"">
                  <model>
                    <EquipmentCode>{equipmentCode}</EquipmentCode>
                    <ResourceCode>{resourceCode}</ResourceCode>
                    <LocalTime>{localTime}</LocalTime>
                    <OperatorUserID>{operatorUserID}</OperatorUserID>
                    <OperatorPassword>{operatorPassword}</OperatorPassword>
                  </model>
                </OperatorLogin>
              </soap12:Body>
            </soap12:Envelope>";

            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://122.195.53.162:7008/EquWebService80/EquToMes/EquToMesOperatorLogin.asmx?op=OperatorLogin",
            }, soapBody, new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "application/soap+xml",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
            });

            var str = result2.ToString();
        }

        /// <summary>
        /// 以http post方式调用webservice，成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button7_Click(object sender, EventArgs e)
        {
            var result2 = await _communicator.PostAsync(new HttpAddress
            {
                RequestUri = "http://192.168.24.25:15000/WebServiceMesDemo.asmx/addition",
            }, "i=21&j=34", new HttpConfig
            {
                Enable = _communicator.Config.Enable,
                ContentType = "application/x-www-form-urlencoded",
                EncodingName = _communicator.Config.EncodingName,
                Timeout = _communicator.Config.Timeout,
                JsonSerializerOptions = _communicator.Config.JsonSerializerOptions,
            });

            var str = result2.ToString();
        }

        /// <summary>
        /// 以http get方式调用webservice，成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button8_Click(object sender, EventArgs e)
        {
            var result2 = await _communicator.GetAsync(new HttpAddress
            {
                RequestUri = "http://192.168.24.25:15000/WebServiceMesDemo.asmx/addition?i=22&j=75",
            });

            var str = result2.ToString();
        }
    }
}
